package com.aistar.service;

import com.aistar.api.Result;
import com.aistar.utils.SendMailUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Service
public class RegistServiceImpl implements RegistService{

    @Autowired
    private JavaMailSender mailSender;//一定要用@Autowired

    @Override
    public Result sentCode(HttpSession session, String email) {

        try {
            // SimpleMailMessage智能执行,邮件的预编辑
            SimpleMailMessage mailMessage = new SimpleMailMessage();

            mailMessage.setSubject("验证码邮件");//主题
            //生成随机数
            String code = SendMailUtils.achieveCode();

            mailMessage.setText("您收到的验证码是："+code);//内容

            //将随机数放置到session中
            session.setAttribute("email",email);
            session.setAttribute("code",code);

            mailMessage.setTo(email);//发给谁

            mailMessage.setFrom("");//你自己的邮箱

            //mailSender需要进行注入,动态加载
            mailSender.send(mailMessage);//发送

            return Result.success();
//            return new Result<>("200","邮件成功发送",null);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed("发送失败,请检查配置");
        }

    }
}
